package stardust.product.platform.webc.log;

import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import stardust.core.support.conversion.StringConversion;
import stardust.product.platform.webc.WebcContext;
import stardust.product.platform.webc.WebcResourceReference;
import stardust.product.platform.webc.annotation.Handler;

public class LogController
{

  @Handler("/webc/log")
  public void showLog(WebcContext context, HttpServletResponse response) throws IOException
  {
    Map<String, WebcResourceReference> referenceMap = context.getContainer().getHandleReference();
    Iterator<String> keys = referenceMap.keySet().iterator();
    String key;
    WebcResourceReference value;
    AccessLog log;
    
    response.setContentType("text/html; charset=utf-8");
    response.getWriter().println("<html><body>");

    response.getWriter().println("<table border=\"1\" width=\"100%\">");
    response.getWriter().println("<tr><th width=\"30%\">URI</th><th width=\"5%\">访问次数</th><th width=\"15%\">最后访问时间</th><th width=\"5%\">平均耗时</th><th width=\"10%\">总计耗时</th> <th width=\"5%\">错误次数</th><th width=\"15%\">最后错误时间</th><th>最后错误信息</th></tr>");
    while (keys.hasNext())
    {
      key = keys.next();
      value = referenceMap.get(key);
      log = value.getAccessLog();
      
      response.getWriter().println("<tr><td>" + key + "</td><td>" + log.getAccessCount() + "</td><td>" + (log.getLastAccessTime() == 0 ? "&nbsp;" : StringConversion.parseDate(new Date(log.getLastAccessTime()), "yyyy-MM-dd HH:mm:ss")) + "</td><td>" + (log.getAccessCount() == 0 ? log.getConsumptionTime() : log.getConsumptionTime() / log.getAccessCount()) + "</td><td>" + log.getConsumptionTime() + "</td><td>" + log.getErrorCount() + "</td><td>" + (log.getLastErrorTime() == 0 ? "&nbsp;" : StringConversion.parseDate(new Date(log.getLastErrorTime()), "yyyy-MM-dd HH:mm:ss")) + "</td><td>" + (log.getLastError() == null ? "&nbsp;" : log.getLastError()) + "</td></tr>");
      response.getWriter().println("</tr>");
    }
    
    response.getWriter().println("</table>");
    
    response.getWriter().println("</body></html>");
  }
  
}
